﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;

namespace QT
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class Tools
    {
        #region Alert

        /// <summary>
        /// 弹出对话框，无参数
        /// </summary>
        public static void Alert()
        {
            string myScript = "window.alert('欢迎使用大秦时代管理系统');";
            Page page = HttpContext.Current.CurrentHandler as Page;
            page.ClientScript.RegisterStartupScript(page.GetType(), "MyScript", myScript, true);
        }

        /// <summary>
        /// 弹出对话框,带参数
        /// </summary>
        /// <param name="mystr">对话框文字</param>
        public static void Alert(string mystr)
        {
            string myScript = "window.alert('" + mystr.Trim() + "');";//去掉mystr前后空格，解决因空格造成换行导致对话框不能弹出的问题
            Page page = HttpContext.Current.CurrentHandler as Page;
            page.ClientScript.RegisterStartupScript(page.GetType(), "MyScript", myScript, true);
        }

        /// <summary>
        /// 弹出对话框，确定后跳转到指定URL
        /// </summary>
        /// <param name="mystr">对话框文字</param>
        /// <param name="newurl">URL地址</param>
        public static void Alert(string mystr, string newurl)
        {
            string myScript = "window.alert('" + mystr.Trim() + "');";//去掉mystr前后空格，解决因空格造成换行导致对话框不能弹出的问题
            myScript += "window.location='" + newurl.Trim() + "';";
            Page page = HttpContext.Current.CurrentHandler as Page;
            page.ClientScript.RegisterStartupScript(page.GetType(), "MyScript", myScript, true);
        }

        #endregion

        #region Encryption

        #region MD5

        /// <summary>
        /// MD5加密，返回加密后的字符串
        /// </summary>
        /// <param name="str">需要加密的明文</param>
        /// <returns>加密后的密文</returns>
        public static string MD5(string str)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
        }

        #endregion

        #region SHA1

        /// <summary>
        /// SHA1加密，返回加密后的字符串
        /// </summary>
        /// <param name="str">需要加密的明文</param>
        /// <returns>加密后的密文</returns>
        public static string SHA1(string str)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1");
        }

        #endregion

        #region 3DES

        private static string sKey = "5tpMC2dovLDHzt/pRr/SOGSJPXANLG51"; //私钥

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="encryptValue">待加密的字符串</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源字符串</returns>
        public static string EncyptString(string encryptValue)
        {
            try
            {
                TripleDES des = new TripleDESCryptoServiceProvider();
                des.Key = Convert.FromBase64String(sKey);
                des.Mode = CipherMode.ECB;

                byte[] valBytes = Encoding.UTF8.GetBytes(encryptValue);
                ICryptoTransform transform = des.CreateEncryptor();

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                cs.Write(valBytes, 0, valBytes.Length);
                cs.FlushFinalBlock();
                byte[] returnBytes = ms.ToArray();
                cs.Close();

                return Convert.ToBase64String(returnBytes);
            }
            catch
            {
                return encryptValue;
            }
        }

        /// <summary>
        /// 加密,带密钥
        /// </summary>
        /// <param name="encryptValue">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源字符串</returns>
        public static string EncyptString(string encryptValue, string encryptKey)
        {
            try
            {
                TripleDES des = new TripleDESCryptoServiceProvider();
                des.Key = Convert.FromBase64String(encryptKey);
                des.Mode = CipherMode.ECB;

                byte[] valBytes = Encoding.UTF8.GetBytes(encryptValue);
                ICryptoTransform transform = des.CreateEncryptor();

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                cs.Write(valBytes, 0, valBytes.Length);
                cs.FlushFinalBlock();
                byte[] returnBytes = ms.ToArray();
                cs.Close();

                return Convert.ToBase64String(returnBytes);
            }
            catch
            {
                return encryptValue;
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="decryptedValue">待解密的字符串</param>
        /// <returns>解密成功返回解密后的字符串，失败返回源字符串</returns>
        public static string DecryptString(string decryptedValue)
        {
            try
            {
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
                des.Key = Convert.FromBase64String(sKey);
                des.Mode = CipherMode.ECB;

                byte[] valBytes = Convert.FromBase64String(decryptedValue);
                ICryptoTransform transform = des.CreateDecryptor();

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                cs.Write(valBytes, 0, valBytes.Length);
                cs.FlushFinalBlock();
                byte[] returnBytes = ms.ToArray();
                cs.Close();

                return Encoding.UTF8.GetString(returnBytes);
            }
            catch
            {
                return decryptedValue;
            }
        }

        /// <summary>
        /// 解密，带密钥
        /// </summary>
        /// <param name="decryptedValue">待解密的字符串</param>
        /// <param name="decryptedKey">解密密钥</param>
        /// <returns>解密成功返回解密后的字符串，失败返回源字符串</returns>
        public static string DecryptString(string decryptedValue, string decryptedKey)
        {
            try
            {
                TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
                des.Key = Convert.FromBase64String(decryptedKey);
                des.Mode = CipherMode.ECB;

                byte[] valBytes = Convert.FromBase64String(decryptedValue);
                ICryptoTransform transform = des.CreateDecryptor();

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
                cs.Write(valBytes, 0, valBytes.Length);
                cs.FlushFinalBlock();
                byte[] returnBytes = ms.ToArray();
                cs.Close();

                return Encoding.UTF8.GetString(returnBytes);
            }
            catch
            {
                return decryptedValue;
            }
        }

        #endregion

        #endregion

        #region ExportData

        #region Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="DataTable">数据来源表</param>
        /// <param name="FileName">文件名</param>
        public static void Export2Excel(DataTable DataTable, string FileName)
        {
            HttpResponse resp;
            Page page = HttpContext.Current.CurrentHandler as Page;
            resp = page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            string colHeaders = "", ls_item = "";
            int i = 0;

            //定义表对象与行对像，同时用DataSet对其值进行初始化 
            DataTable dt = DataTable;
            DataRow[] myRow = dt.Select("");
            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            for (i = 0; i < dt.Columns.Count - 1; i++) colHeaders += dt.Columns[i].Caption.ToString() + "\t";
            colHeaders += dt.Columns[i].Caption.ToString() + "\n";
            //向HTTP输出流中写入取得的数据信息 
            resp.Write(colHeaders);
            //逐行处理数据 
            foreach (DataRow row in myRow)
            {
                //在当前行中，逐列获得数据，数据之间以\t分割，结束时加回车符\n 
                for (i = 0; i < dt.Columns.Count - 1; i++) ls_item += row[i].ToString() + "\t";
                ls_item += row[i].ToString() + "\n";
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据 
                resp.Write(ls_item);
                ls_item = "";
            }
            //写缓冲区中的数据到HTTP头文件中 
            resp.End();
        }

        /// <summary>
        /// 导出Excel，列名自定义
        /// </summary>
        /// <param name="DataTable">数据来源表</param>
        /// <param name="FileName">文件名</param>
        /// <param name="Columns">列名，用“，”分隔</param>
        public static void Export2Excel(DataTable DataTable, string FileName, string Columns)
        {
            HttpResponse resp;
            Page page = HttpContext.Current.CurrentHandler as Page;
            resp = page.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            string colHeaders = "", ls_item = "";
            int i = 0;
            string[] cols = Columns.Split(',');

            //定义表对象与行对像，同时用DataSet对其值进行初始化 
            DataTable dt = DataTable;
            DataRow[] myRow = dt.Select("");
            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            for (i = 0; i < dt.Columns.Count - 1; i++) colHeaders += cols[i].ToString() + "\t";
            colHeaders += cols[i].ToString() + "\n";
            //向HTTP输出流中写入取得的数据信息 
            resp.Write(colHeaders);
            //逐行处理数据 
            foreach (DataRow row in myRow)
            {
                //在当前行中，逐列获得数据，数据之间以\t分割，结束时加回车符\n 
                for (i = 0; i < dt.Columns.Count - 1; i++) ls_item += row[i].ToString() + "\t";
                ls_item += row[i].ToString() + "\n";
                //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据 
                resp.Write(ls_item);
                ls_item = "";
            }
            //写缓冲区中的数据到HTTP头文件中 
            resp.End();
        }

        #endregion

        #endregion
    }
}
